package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
	"weibo-mgr/cache"
	"weibo-mgr/models"
)

func List(c *gin.Context) {
	var weibo []models.WeiBo
	redis_key := "weibo_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&weibo).Debug()
		jsonData, _ := json.Marshal(weibo)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &weibo)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": weibo,
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var weibo models.WeiBo
	redis_key := "novel_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&weibo).Debug()
		jsonData, _ := json.Marshal(weibo)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &weibo)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": weibo,
	})
	return

}
